var currentuser = undefined;
var currentOptpmtryId=undefined;
var currentOptpmtryIdarray=[];
var is_leave = false;
var sales_id = undefined;
var page_type = 'retail';
$(function(){
	function searcharchives() {
		layer.open({
			type: 2
			, skin: 'layui-layer-molv'
			, title: false
			, shadeClose: false
			, shade: 0.2
			, id: 'search_archives_dialog'
			, area: ['1000px', '600px']
			, content: seelct_archives_url
			, anim: 1 //动画类型
			,end: function(){
				if($('#archives_id').val() == 0) {
					location.href = reail_index_url;
				}
			}
		});
	}
	searcharchives();
	//切换用户
	$('#rechange').click(function(){
		emptyOptometry();
		searcharchives();
	});
	//修改资料
	$('#editarchives').click(function () {
		actionArchives($('#archives_id').val());
		return false;
	});

	$('#addarchives').click(function() {
		layer.open({
			type: 2
			, title: '<i class="fa fa-cog"></i>&nbsp;新增档案'
			, shadeClose: true
			, shade: 0.2
			, id: 'search_archives_dialog'
			, area: ['1000px', "540px"]
			, content: [archives_edit_url + '/0']
			, anim: 1 //动画类型
		});
		return false;
	});

	//点选历史处方
	$(".historybar > ul").on("click", "li[data-day][data-day!='more'] > a", function() {
		var id = $(this).parent().data("day");
		if(id=="today"&&!currentuser)
			return;
		$(".historybar > ul > li[data-day] > a").removeClass("active");
		$(this).addClass("active");
		$(".yanguang > .yg-info[data-day]").hide();
		$(".yanguang > .yg-info[data-day='" + id + "']").show();
	});
	
	//处方更多
	$(".historybar > ul").on("click", "li[data-day='more'] > a", function() {
		layer.open({
			type: 2
			, title: '更多验光记录'
			, shade: 0.2
			, id: 'viewOptometry_dialog'
			, area: ['80%', '70%']
			, content: [get_optometry_more_url+'?archives_id='+currentuser.Id+'&currentOptpmtryId='+currentOptpmtryId]
			, anim: 1 //动画类型
		});
		return false;
	});

	//处方类型切换
	$(".yanguang > .yg-info[data-day]").on("click", ".chufang > .title > ul > li > a", function() {
		var id = $(this).parents(".yg-info:eq(0)").data("day");
		var type = $(this).data("type");
		$(".yanguang > .yg-info[data-day='" + id + "'] > .chufang > .title > ul > li > a").removeClass("active");
		$(this).addClass("active");
		$(".yanguang > .yg-info[data-day='" + id + "'] > .chufang > .datatable-shili").hide();
		$(".yanguang > .yg-info[data-day='" + id + "'] > .chufang > .datatable-shili[data-type='" + type + "']").show();
	});

	//历史处方内容复制
	$(".yanguang").on("click", ".yg-info[data-day][data-day!='today'] > .chufang > .datatable-shili > .clone-btn", function() {
		if(!$(this).parent().find(".info-bar[data-type]:first").find(".item:first").text()&&!$(this).parent().find(".info-bar[data-type]:last").find(".item:first").text()){
			layer.alert("请勿引用空数据");
			return;
		}
		var st = $(this).parent().data("type");
		$(this).parent().find(".info-bar[data-type] > .item").each(function(i) {
			var pt = $(this).parent().data("type");
			var t = $(this).data("type");
			$(".yanguang > .yg-info[data-day='today'] > .chufang > .datatable-shili[data-type='" + st + "']").attr("copy","false");//加上引用标识
			$(".yanguang > .yg-info[data-day='today'] > .chufang > .datatable-shili[data-type='" + st + "']").attr("saved","true");//加上保存标识
			if($(this).text()){
				$(".yanguang > .yg-info[data-day='today'] > .chufang > .datatable-shili[data-type='" + st + "'] > .info-bar[data-type='" + pt + "'] > .item[data-type='" + t + "']").text($(this).text());
			}
		});
		$(this).parent().find(".info-bar.define-row > .item > .pmr > em").each(function(i) {
			if($(this).text()){
				$(".yanguang > .yg-info[data-day='today'] > .chufang > .datatable-shili[data-type='" + st + "'] > .info-bar.define-row > .item > .pmr > em:eq(" + i + ")").text($(this).text());
			}
		});
		$(".historybar > ul > li[data-day='today'] > a").click();
		$(".yanguang > .yg-info[data-day='today'] > .chufang > .title > ul > li > a[data-type='" + st + "']").click();
	});
	
	//处方内容清除
	$(".yanguang").on("click", ".yg-info[data-day='today'] > .chufang > .datatable-shili > .clear-btn", function() {
		$(this).parent().attr("copy","false");//清除引用标识
		$(this).parent().attr("saved","false");//清除保存标识
		$(this).parent().find(".info-bar[data-type] > .item").html("&nbsp;");
		$(this).parent().find(".info-bar.define-row > .item > .pmr > em").html("&nbsp;");
	});

	//扫码添加
	$("#scan_add_goods").on("click",function() {
		layer.alert("功能开发中");
	});
	//添加服务
	$("#add_service").on("click",function() {
		layer.alert("功能开发中");
	});
	//添加商品
	$("#add_new_goods").on("click",function() {
		var type =undefined;
		var sph_left =undefined;
		var sph_right =undefined;
		var cyl_left =undefined;
		var cyl_right =undefined;
		var axial_view_left=undefined;
		var axial_view_right=undefined;
		var diameter_left=undefined;
		var diameter_right=undefined;
		var base_curve_left=undefined;
		var base_curve_right=undefined;
		var add_info_left=undefined;
		var add_info_right=undefined;
		var pass_left=undefined;
		var pass_right=undefined;
		var st = $(".yanguang.shadow.mb20 > .yg-info[data-day='today'] > .chufang > .title > ul > li > a[class='active']").attr("data-type");
		$(".yanguang > .yg-info[data-day='today'] > .chufang  > .datatable-shili[data-type='" + st + "'] > .info-bar[data-type] > .item").each(function(i){
			var pt = $(this).parent().data("type");
			var t = $(this).data("type");
			type=st;
			if(pt=="left"&&t=="sph"){
				sph_left = removeSpace($(this).text());
			}else if(pt=="right"&&t=="sph"){
				sph_right = removeSpace($(this).text());
			}else if(pt=="left"&&t=="cyl"){
				cyl_left = removeSpace($(this).text());
			}else if(pt=="right"&&t=="cyl"){
				cyl_right = removeSpace($(this).text());
			}else if(pt=="left"&&t=="add_info"){
				add_info_left = removeSpace($(this).text());
			}else if(pt=="right"&&t=="add_info"){
				add_info_right = removeSpace($(this).text());
			}
		});
		layer.open({
			type: 2
			, title: false
			, shade: 0.2
			, id: 'inventory_product_list_new_url'
			, area: ['1000px', '700px']
			, content: [inventory_product_list_new_url]
			, anim: 1 //动画类型
		});
		return false;

	});

	//添加历史商品
	$("#add_hisoty_goods").on("click",function() {
		layer.open({
			type: 2
			, title: false
			, shade: 0.2
			, id: 'inventory_product_list_new_url'
			, area: ['1000px', '700px']
			, content: [hisoty_product_list_url+'?archives_id='+currentuser.Id]
			, anim: 1 //动画类型
		});
		return false;
	});

	//添加服务
	$("#add_service").on("click",function() {

	});
   
	//商品定制
	$('#add_custom_goods').on('click', function () {
		layer.open({
			type: 2
			, title: false
			, shade: 0.2
			, id: 'inventory_product_list_new_url'
			, area: ['1000px', '700px']
			, content: [custom_product_list_new_url]
			, anim: 1 //动画类型
		});
		return false;
	})
	
});

//接收选择的顾客
function receiveFormData(d) {
	if(!d) return false;
	$('#birthday').text(d.Birthday);
	$('#sex').text(d.Sex);
	$('#mobile').text(d.Mobile);
	$('#realname').text(d.Realname);
	$('#archives_id').val(d.Id);
	currentuser = d;  //设置当前用户

	$.post(get_optometry_url, {'archives_id':d.Id}, function (res) {
		loadedOptometry(res.data);
	});
	layer.closeAll('iframe');
}

function dialogReback(d) {
	receiveFormData(d);
}

//获取单条更多数据引用
function getMoreOptometryData(id, chufang_type) {
	$.post(get_optometry_one_url+'?opt_id='+id, function (res) {
		if(res.code == 1) {
			layer.alert(res.msg);return false;
		}
		var _data = [];
		_data.push(res.data);
		loadedOptometry(_data);
		$(".yanguang > .yg-info[data-day='" + id + "'] > .chufang > .datatable-shili[data-type='" + chufang_type + "']").find("a[class='clone-btn']").click();
	}, 'json');
}

var emptyOptometry= function(){
	$(".historybar").find("li[data-day!='today'][data-day!='more']").remove();
	$(".yanguang > .yg-info[data-day!='today']").remove();
};
var loadedOptometry = function(his) {
	for (var i in his) {
		var opt = his[i];
		var chufang = opt.chufang;

		currentOptpmtryIdarray.push(opt.Id);//将验光单ID记录到内存，查看更多验光信息的时候需要去除掉
		var tab = $(".historybar").find("li[data-day='today']").clone();
		tab.find('a').removeClass("active");
		tab.attr("data-day", opt.Id);
		tab.find("a").text(timetransDate(opt.CreatedAt));
		$(".historybar").find("li[data-day='more']").before(tab);

		var box = $(".yanguang > .yg-info[data-day='today']").clone(true);
		box.attr("data-day", opt.Id);
		box.find(".tab-lei a").attr('data-tid', opt.Id);
		box.find(".item").attr('contenteditable', false);
		box.find(".datatable-shili > .clear-btn").removeClass("clear-btn").addClass("clone-btn");
		box.find(".datatable-shili > .clone-btn > i").removeClass("icon-clear").addClass("icon-switch");
		box.find(".datatable-shili > .clone-btn").html('<i class="am-icon-exchange"></i>引用');
		box.find(".datatable-shili > .info-bar[data-type] > .item").text("");
		box.find(".datatable-shili > .info-bar.define-row > .item > .pmr > em").text("");
		box.hide();

		box.find(".form-bar .optist").html("<div class=\"select-hst\"><span>"+opt.Optometrist+"</span></div>");
		box.find(".form-bar .doctor").html("<div class=\"select-hst\"><span>"+opt.Doctor+"</span></div>");
		if(opt.Remarks){
			box.find(".form-bar .remarks").html("<div class=\"select-hst\"><span>"+ opt.Remarks +"</span></div>");
		}else{
			box.find(".form-bar .remarks").html("<div class=\"select-hst\"><span></span></div>");
		}

		for (var o in chufang) {
			if (chufang[o]) {
				for(var k in chufang[o]) {
					for(var kk in chufang[o][k]) {
						if(chufang[o][k][kk]) {
							box.find(".datatable-shili[data-type='" + chufang[o][k].type_name + "'] > .info-bar[data-type='" + k + "'] > .item[data-type='" + kk + "']").text(chufang[o][k][kk]);
						} else {
							box.find(".datatable-shili[data-type='" + chufang[o][k].type_name + "'] > .info-bar[data-type='" + k + "'] > .item[data-type='" + kk + "']").html("&nbsp;");
						}
					}
				}
				if(o == "far"){
					box.find(".datatable-shili[data-type='far'] > .info-bar.define-row > .item > .pmr[data-type='total_pd_yuan'] > em").text(chufang[o]['right']["total_pd_yuan"]);
				}else if(o == "near"){
					box.find(".datatable-shili[data-type='near'] > .info-bar.define-row > .item > .pmr[data-type='total_pd_jin'] > em").text(chufang[o]['right']["total_pd_jin"]);
				}else if(o == "duojiaodian"){
					box.find(".datatable-shili[data-type='duojiaodian'] > .info-bar.define-row > .item > .pmr[data-type='total_pd_jin'] > em").text(chufang[o]['right']["total_pd_jin"]);
					box.find(".datatable-shili[data-type='duojiaodian'] > .info-bar.define-row > .item > .pmr[data-type='total_pd_yuan'] > em").text(chufang[o]['right']["total_pd_yuan"]);
				}
			}
		}
		$(".yg-info[data-day='today']").after(box);
	}
	currentOptpmtryId = currentOptpmtryIdarray.join(",");//将验光单ID记录到内存，查看更多验光信息的时候需要去除掉
};
var addGoods = function(goods) {
	var box = $("#goodslist > .goodsrow[template='template']").clone();
	box.removeAttr("template");
	/*********将需要的数据加载到tr行上面去，循环组装数据***************/
	goods.discount = 100;
	goods.sale_num = 1;
	goods.SuggestedPrice = goods.suggested_price;
	box.attr("data_type",'goods');
	box.attr("id",goods.Products.Id);
    box.attr("inventory_id", goods.Id);
	box.attr("goods_snd_id",goods.Snd.id);
	box.attr("reserve_num",goods.purchase_num);
	box.attr("custom_id",goods.custom_id);
	box.attr("sale_num",1);
	box.attr("sell_prirce",goods.SuggestedPrice);
	box.attr("single_price",goods.SuggestedPrice);
	box.attr("subtotal",goods.SuggestedPrice * goods.sale_num * (goods.discount/100));
	box.attr("discount",goods.discount);
	/*********************************************/
	box.find(".item.good-name").html(goods.name);
	for (var o in goods.subparams) {
		if(o>0){
			box.find(".item.good-name").next().next().append("<span class='am-margin-left-sm'>" + goods.subparams[o] + "</span>");
		}else{
			box.find(".item.good-name").next().next().append("<span>" + goods.subparams[o] + "</span>");
		}
	}
	box.find(".item.good-price.b.am-text-danger").text("￥" + formatnumber(goods.SuggestedPrice, "#,##0.00"));
	box.find("input[name='sale_num']").val(goods.sale_num);
	box.find("input[name='single_price']").val(goods.SuggestedPrice);
	box.find("input[name='discount']").val(goods.discount);
	box.find("input[name='subtotal']").val((goods.SuggestedPrice * goods.sale_num) * (goods.discount / 100));

	if (!goods.custom_id) {
		box.find(".customize-tips").hide();
	}else{
		box.find(".customize-tips").show();
	}
	$("#goodslist").append(box);
	box.show();
	mathTotalPrice();
	layer.closeAll();
};

var addService = function(service) {
	var box = $("#goodslist > .goodsrow[template='template']").clone();
	box.removeAttr("template");
	/*********将需要的数据加载到tr行上面去，循环组装数据***************/
	box.attr("data_type",service.data_type);
	box.attr("id",service.id);
	box.attr("price",service.price);
	box.attr("sell_prirce",service.price);
	box.attr("serve_name",service.name);
	/*********************************************/
	box.find(".item.good-name").text(service.name);
	for (var o in service.subparams) {
		box.find(".item.good-name").next().append("<span>" + service.subparams[o] + "</span>");
	}
	box.find(".item.good-price.b.color-red").text("￥" + formatnumber(service.price/100, "#,##0.00"));
	box.find("input[name='sale_num']").val(1);
	box.find("input[name='sale_num']").attr("style","background:#dedede;");
	box.find("input[name='sale_num']").parent().find("button").remove();
	box.find("input[name='single_price']").val((service.price/100));
	box.find("input[name='discount']").val(100);
	box.find("input[name='discount']").attr("readonly","readonly");
	box.find("input[name='discount']").attr("style","background:#dedede;");
	box.find("input[name='subtotal']").val((service.price/100));
	box.find("input[name='subtotal']").attr("readonly","readonly");
	box.find("input[name='subtotal']").attr("style","background:#dedede;");
	box.find(".customize-tips").hide();
	$("#goodslist").append(box);
	box.show();
	mathTotalPrice();
};


function removeSpace(text){
	return $.trim(text);
}

function deleteGoods(i) {
	$(i).parent().parent().remove();
	mathTotalPrice();
}
function change_sale_num(obj,type){//修改数量时执行
	if(type=="add"){
		var new_sale_num = parseInt($(obj).parent().find("input[name='sale_num']").val())+1;
		if(new_sale_num<1){
			new_sale_num=1;
		}
		$(obj).parent().find("input[name='sale_num']").val(new_sale_num);
	} else if(type=="sub"){
		var new_sale_num = parseInt($(obj).parent().find("input[name='sale_num']").val())-1;
		if(new_sale_num<1){
			new_sale_num=1;
		}
		$(obj).parent().find("input[name='sale_num']").val(new_sale_num);
	} else if(type == 'ipt') {

	}
	var single_price = $(obj).parent().parent().parent().find("input[name='single_price']").val();
	var sale_num = parseInt($(obj).parent().find("input[name='sale_num']").val());
	$(obj).parent().parent().parent().find("input[name='subtotal']").val(single_price*sale_num);
	changeTRdataInfo();
}
function changeSinglePrice(obj){//修改单价时时执行
	var single_price = $(obj).val();
	var sale_num =$(obj).parent().parent().find("input[name='sale_num']").val();
	$(obj).parent().parent().find("input[name='subtotal']").val(single_price*sale_num);
	changeTRdataInfo();
}
function changeDiscount(obj){//修改折扣时执行
	var sell_prirce =$(obj).parent().parent().attr("sell_prirce");
	var discount = $(obj).val();
	var siglePrice = (sell_prirce*1*(discount*1/100)).toFixed(2);
	$(obj).parent().parent().find("[name='single_price']").val(siglePrice);
	changeSinglePrice($(obj).parent().parent().find("[name='single_price']"));
	changeTRdataInfo();
}
function changeTRdataInfo(){//修改每一行Tr 上的数据
	$("#goodslist").find(".goodsrow").each(function(){
		if($(this).attr("id")){
			if($(this).attr("data_type")=="goods"){
				$(this).attr("sale_num",$(this).find("input[name='sale_num']").val());
				$(this).attr("single_price",parseFloat($(this).find("input[name='single_price']").val()));
				$(this).attr("subtotal",parseFloat($(this).find("input[name='subtotal']").val()));
				$(this).attr("discount",$(this).find("input[name='discount']").val());
			}else{
				$(this).attr("price",parseFloat($(this).find("input[name='single_price']").val()));
			}
		}
	});
	mathTotalPrice();
}
function mathTotalPrice(){
	var total_sell_price=0;
	var total_price=0;
	var i=0;
	$("#goodslist").find(".goodsrow").each(function(){
		if($(this).attr("id")){
			if($(this).attr("data_type")=="goods"){
				total_sell_price= total_sell_price+$(this).attr("sell_prirce")*1*$(this).attr("sale_num");
				total_price=total_price+$(this).attr("subtotal")*1;
			}else{
				total_sell_price= total_sell_price+$(this).attr("sell_prirce")*1;
				total_price=total_price+$(this).attr("price")*1;
			}
			i++;
		}
	});
	/****************商品清单数量显示******************/
	$(".goodsList").parent().parent().find('div[data-type="goods_number"]').html("选择商品("+i+")");
	/*********************************/
	/************显示金额*****************/
	$(".balance-info").find(":first").children(":first").find("span").text("￥" + formatnumber(total_sell_price, "#,##0.00"));
	$(".balance-info").find(":first").children(":last").prev().prev().prev().find("span").text("￥" + formatnumber((total_sell_price-total_price), "#,##0.00"));
	$(".summary-bar").find("span").text("￥" + formatnumber((total_price), "#,##0.00"));
	/***********************************/
	/************保存金额*****************/
	$(".balance-info").find("input[name='sell_total_price']").val(total_sell_price);
	$(".balance-info").find("input[name='total_price']").val(total_price);
	$(".balance-info").find("input[name='total_real_price']").val(total_price);
	$(".balance-info").find("input[name='preferential_total_price']").val(total_sell_price-total_price);
	/***********************************/
}

function changePickType(obj){
	$(obj).parent().find("a").removeClass();
	$(obj).addClass("active");
	if($(obj).attr("pick_up_type")==1){
		$("input[name='address_name']").parent().parent().hide();
		$("input[name='hope_pick_up_time']").parent().parent().hide();
	}else if($(obj).attr("pick_up_type")==2){
		$("input[name='hope_pick_up_time']").parent().parent().hide();
		var associator_id =currentuser.Id;
		if(associator_id){
			$("input[name='address_name']").parent().parent().show();
			$("input[name='address_name']").val(currentuser.Address);
		}else{
			layer.msg("请选择会员");
			return;
		}
	}else{
		$("input[name='hope_pick_up_time']").parent().parent().show();
		$("input[name='address_name']").parent().parent().hide();
	}
}
function changeAssociatorPoint(obj){
	$(obj).parent().find("a").removeClass();
	$(obj).addClass("active");
}

//获取验光数据
function getOptData() {
	var data=[];
	/*****************组装验光数据**********************/
	var far =[];
	var naer=[];
	var yinxing=[];
	var dojiaodian=[];

	var o_json ={};
	var box = $(".yg-info[data-day='today']");
	box.find("div.chufang").find(".datatable-shili[data-type='far'][saved='true']").find(".info-bar").each(function(){
		if($(this).attr("data-type")){
			o_json={};
			o_json.type_name = 'far';
			o_json.sph = $(this).find("div[data-type='sph']").text();
			o_json.cyl = $(this).find("div[data-type='cyl']").text();
			o_json.axial_view = $(this).find("div[data-type='axial_view']").text();
			o_json.pd_yuan= $(this).find("div[data-type='pd_yuan']").text();
			o_json.mrp = $(this).find("div[data-type='mrp']").text();
			o_json.nv = $(this).find("div[data-type='nv']").text();
			o_json.cv = $(this).find("div[data-type='cv']").text();
			o_json.v = $(this).find("div[data-type='v']").text();
			o_json.bc = $(this).find("div[data-type='bc']").text();
			o_json.total_pd_yuan = box.find("div.chufang").find(".datatable-shili[data-type='far'][saved='true']").find(".info-bar:last").find("[data-type='total_pd_yuan']").find("em").text();
			if($(this).attr("data-type")=="left"){
				o_json.eye_type = 'left';
			}else if($(this).attr("data-type")=="right"){
				o_json.eye_type = 'right';
			}
			far.push(o_json);
		}
	});

	box.find("div.chufang").find(".datatable-shili[data-type='near'][saved='true']").find(".info-bar").each(function(){
		if($(this).attr("data-type")){
			o_json={};
			o_json.type_name = 'near';
			o_json.sph = $(this).find("div[data-type='sph']").text();
			o_json.cyl = $(this).find("div[data-type='cyl']").text();
			o_json.axial_view = $(this).find("div[data-type='axial_view']").text();
			o_json.pd_jin= $(this).find("div[data-type='pd_jin']").text();
			o_json.mrp = $(this).find("div[data-type='mrp']").text();
			o_json.nv = $(this).find("div[data-type='nv']").text();
			o_json.cv = $(this).find("div[data-type='cv']").text();
			o_json.v = $(this).find("div[data-type='v']").text();
			o_json.bc = $(this).find("div[data-type='bc']").text();
			o_json.total_pd_jin = box.find("div.chufang").find(".datatable-shili[data-type='near'][saved='true']").find(".info-bar:last").find("[data-type='total_pd_jin']").find("em").text();
			if($(this).attr("data-type")=="left"){
				o_json.eye_type = 'left';
			}else if($(this).attr("data-type")=="right"){
				o_json.eye_type = 'right';
			}
			naer.push(o_json);
		}
	});

	box.find("div.chufang").find(".datatable-shili[data-type='yinxing'][saved='true']").find(".info-bar").each(function(){
		if($(this).attr("data-type")){
			o_json={};
			o_json.type_name = 'yinxing';
			o_json.sph = $(this).find("div[data-type='sph']").text();
			o_json.cyl = $(this).find("div[data-type='cyl']").text();
			o_json.axial_view = $(this).find("div[data-type='axial_view']").text();
			o_json.pd_jin= $(this).find("div[data-type='pd_jin']").text();
			o_json.mrp = $(this).find("div[data-type='mrp']").text();
			o_json.nv = $(this).find("div[data-type='nv']").text();
			o_json.cv = $(this).find("div[data-type='cv']").text();
			o_json.diameter = $(this).find("div[data-type='diameter']").text();
			o_json.base_curve = $(this).find("div[data-type='base_curve']").text();

			if($(this).attr("data-type")=="left"){
				o_json.eye_type = 'left';
			}else if($(this).attr("data-type")=="right"){
				o_json.eye_type = 'right';
			}
			yinxing.push(o_json);
		}
	});
	box.find("div.chufang").find(".datatable-shili[data-type='duojiaodian'][saved='true']").find(".info-bar").each(function(){
		if($(this).attr("data-type")){
			o_json={};
			o_json.type_name = 'duojiaodian';
			o_json.sph = $(this).find("div[data-type='sph']").text();
			o_json.cyl = $(this).find("div[data-type='cyl']").text();
			o_json.axial_view = $(this).find("div[data-type='axial_view']").text();
			o_json.pd_jin= $(this).find("div[data-type='pd_jin']").text();
			o_json.pd_yuan= $(this).find("div[data-type='pd_yuan']").text();
			o_json.mrp = $(this).find("div[data-type='mrp']").text();
			o_json.nv = $(this).find("div[data-type='nv']").text();
			o_json.cv = $(this).find("div[data-type='cv']").text();
			o_json.add_info = $(this).find("div[data-type='add_info']").text();
			o_json.pass = $(this).find("div[data-type='pass']").text();
			o_json.v = $(this).find("div[data-type='v']").text();
			o_json.bc = $(this).find("div[data-type='bc']").text();
			o_json.total_pd_jin = box.find("div.chufang").find(".datatable-shili[data-type='duojiaodian'][saved='true']").find(".info-bar:last").find("[data-type='total_pd_jin']").find("em").text();
			o_json.total_pd_yuan = box.find("div.chufang").find(".datatable-shili[data-type='duojiaodian'][saved='true']").find(".info-bar:last").find("[data-type='total_pd_yuan']").find("em").text();
			if($(this).attr("data-type")=="left"){
				o_json.eye_type = 'left';
			}else if($(this).attr("data-type")=="right"){
				o_json.eye_type = 'right';
			}
			dojiaodian.push(o_json);
		}
	});
	data = $.merge([], far);
	data = $.merge(data, naer);
	data = $.merge(data, yinxing);
	data = $.merge(data, dojiaodian);


	var o_valid = false;
	box.find("div.chufang").find(".datatable-shili[data-type][copy='false']").each(function(){
		if($(this).attr("saved")=="true"){
			o_valid= true;
		}
	});
	if(o_valid){
		if(!$("select[name='optometrist']").val()){
			layer.alert("请选择验光师");
			return false;
		}
	}
	return data;
}

function save(){
	var data={};
	data.pick_up_type=$(".lable-select").find("a.active[pick_up_type]").attr("pick_up_type");
	data.associator_id=currentuser.Id;
	data.sale_person = $("select[name='business_id']").val();
	data.sale_person_name = $("select[name='business_id']:selected").text();
	data.remark = $("input[name='remark']").val();

	opt = getOptData();
	if(opt === false) {
		return;
	}
	if(opt.length > 0) {
		data.chufang = JSON.stringify(opt);
		data.doctor = $("select[name='doctor']").val();
		data.optremark = $("input[name='optremark']").val();
		data.optometrist = $("select[name='optometrist']").val();
	}

	if(!data.sale_person){
		layer.alert("请选配镜顾问");
		return;
	}

	/****************************************/
	data.goods_data=[];
	data.serve_data=[];
	if(data.pick_up_type=="2"&&(!$("input[name='address_name']").val())){
		layer.alert("因选择邮递取货请填入收货地址");
		return;
	}else if(data.pick_up_type=="3"&&(!$("input[name='hope_pick_up_time']").val())){
		layer.alert("因使用指定时间取货，请填写指定日期");
		return;
	}
	$("#goodslist").find(".goodsrow").each(function(){
		if($(this).attr("id")){
			var goods_json={};
			var service_json={};
			if($(this).attr("data_type")=="goods"){
				goods_json.discount=$(this).attr("discount");
				goods_json.goods_snd_id=$(this).attr("goods_snd_id");
				goods_json.id=$(this).attr("id");
                goods_json.inventory_id=$(this).attr("inventory_id");
				goods_json.reserve_num=$(this).attr("reserve_num");
				goods_json.sale_num=$(this).attr("sale_num");
				goods_json.sell_prirce=$(this).attr("sell_prirce");
				goods_json.single_price=$(this).attr("single_price");
				goods_json.subtotal=$(this).attr("subtotal");
				goods_json.custom_id=$(this).attr("custom_id");
				data.goods_data.push(goods_json);
			}else{
				service_json.id=$(this).attr("id");
				service_json.serve_name=$(this).attr("serve_name");
				service_json.price=$(this).attr("price");
				data.serve_data.push(service_json);
			}
		}
		
	});
	if(data.goods_data.length<=0&&data.serve_data.length<=0){
		layer.alert("请添加商品或服务");
		return;
	}

	data.sales_id=sales_id;
	data.address_name=$("input[name='address_name']").val();
	data.hope_pick_up_time=$("input[name='hope_pick_up_time']").val();
	data.preferential_total_price=$("input[name='preferential_total_price']").val();
	data.sell_total_price=$("input[name='sell_total_price']").val();
	data.total_price=$("input[name='total_price']").val();
	data.total_real_price=$("input[name='total_real_price']").val();
	data.remark = $("input[name='remark']").val();

	var i=0;
	var j=0;
	for(var index in data.goods_data){
		if((parseInt(data.goods_data[index].reserve_num)<parseInt(data.goods_data[index].sale_num))&&(data.pick_up_type==1)){
			layer.alert("商品存在无货销售,取货方式应为指定时间取货或邮递取货");
			return;
		}else if((data.goods_data[index].goods_custom_id)&&data.pick_up_type==1){
			layer.alert("因存在定制商品,取货方式应为指定时间取货或邮递取货");
			return;
		}
		if(parseInt(data.goods_data[index].reserve_num)<parseInt(data.goods_data[index].sale_num)){
			i++;
		}else if((data.goods_data[index].goods_custom_id)){
			j++;
		}
	}

	data.goods_data = JSON.stringify(data.goods_data);
	data.serve_data = data.serve_data.length > 0 ? JSON.stringify(data.serve_data) : '';
	if(i>0){
		layer.confirm("因存在无货销售行为,请及时处理该库存", function(c) {
			layer.close(c);
			$.post(save_add_sales_url, data, function (res) {
				if(res.code == 1) {
					layer.alert(res.msg);
					return false
				}
				saveAndChange(res.data,data);
			}, 'json');
		});
	}else{
		if(j>0){
			layer.confirm("因存在定制商品,请及时处理该库存", function(c) {
				layer.close(c);
				$.post(save_add_sales_url, data, function (res) {
					if(res.code == 1) {
						layer.alert(res.msg);
						return false
					}
					saveAndChange(res.data,data);
				}, 'json');
			});
		}else{
			$.post(save_add_sales_url, data, function (res) {
				if(res.code == 1) {
					layer.alert(res.msg);
					return false
				}
				saveAndChange(res.data,data);
			}, 'json');
		}
	}
}

function saveAndChange(salesid,data){
	sales_id = salesid;
	is_leave=true;
	if(data.pick_up_type==1||data.pick_up_type==3){
		layer.open({
			type: 2
			, title: '取镜结算'
			, shadeClose: true
			, shade: 0.2
			, id: 'search_archives_dialog'
			, area: ['100%', "100%"]
			, content: [pickup_pay_confirm_url + '?sales_id='+ sales_id]
			, anim: 1 //动画类型
			,cancel: function(index, layero){
				is_leave = false;
				layer.close(index);
				return false;
			}
		});
	}else{
		layer.open({
			type: 2
			, title: '发货结算'
			, shadeClose: true
			, shade: 0.2
			, id: 'search_archives_dialog'
			, area: ['100%', "100%"]
			, content: [sendout_pickup_pay_confirm_url + '?sales_id='+ sales_id]
			, anim: 1 //动画类型
			,cancel: function(index, layero){
				is_leave = false;
				layer.close(index);
				return false;
			}
		});
	}
}

window.onbeforeunload = function (event){
	if(currentuser&&is_leave==false){
		return false;
	}
}
window.onunload = function (event){
	if(sales_id&&is_leave==false){
		$.post(save_clear_sales_url, {'sales_id':sales_id}, function () {});
	}
};

//验光处方具体光度块点击
$(".yg-info[data-day='today']").on("blur", ".chufang > .datatable-shili > .info-bar > .item[data-type]", function() {
	var box = $(".yg-info[data-day='today']");
	var p_type=$(this).parent().parent().attr("data-type");
	var d_type = $(this).data('type');
	var new_va = removeSpace($(this).text());
	if(new_va == '') {
		return;
	}
	box.find("div.chufang").find(".datatable-shili[data-type='"+p_type+"']").attr("saved","true");
	if((p_type=="far"||p_type=="near"||p_type=="duojiaodian")&&(d_type=="pd_yuan"||d_type=="pd_jin")){
		box.find("div.chufang").find(".datatable-shili[data-type='"+p_type+"']").find("div[data-type='left']").next().find(".item > .pmr[data-type='total_"+d_type+"'] > em").text("");
		var total=0;
		$(this).parents(".datatable-shili").find("div.item[data-type='"+d_type+"']").each(function(){
			total = Number($(this).text())+total;
		});
		console.log(total);
		box.find("div.chufang").find(".datatable-shili[data-type='"+p_type+"']").find("div[data-type='left']").next().find(".item > .pmr[data-type='total_"+d_type+"'] > em").text(total);
	}

	if(d_type=="sph"||d_type=="cyl"){//球镜柱镜数值处理下
		new_va = formatnumber(new_va, "0.00");
		if(new_va>0){
			new_va = "+"+new_va;
		}else if(new_va==0){
			new_va  = new_va.toString()+".00";
		}
	}else if(d_type=="nv"||d_type=="cv"){
		new_va = formatnumber(new_va, "0.0");
	}
	$(this).text(new_va);
});